package com.zq.springadmin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zq.springadmin.dao.dto.AssginMenuDto;
import com.zq.springadmin.dao.entity.Permission;
import com.zq.springadmin.dao.entity.RolePermission;
import com.zq.springadmin.mapper.RolePermissionMapper;

import com.zq.springadmin.service.IPermissionService;
import com.zq.springadmin.service.IRolePermissionService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 张乔
 * @since 2024-04-26
 */
@Service
public class RolePermissionServiceImpl extends ServiceImpl<RolePermissionMapper, RolePermission> implements IRolePermissionService {

    @Resource
    private IPermissionService permissionService;


    //查询所有菜单，并返回角色拥有的菜单
    @Override
    public Map<String, Object> findSysRoleMenuByRoleId(Integer roleId) {
        // 查询所有的菜单数据
        List<Permission> permissionList = permissionService.getAll() ;

        // 查询当前角色的菜单数据
        List<RolePermission> list1 = this.list(new LambdaQueryWrapper<RolePermission>()
                .eq(RolePermission::getRoleId, roleId)
                .eq(RolePermission::getIsHalf, 0));
        List<Integer> roleMenuIds = list1.stream().
                map(RolePermission::getPermissionId).toList();

        // 将数据存储到Map中进行返回
        Map<String , Object> result = new HashMap<>() ;
        result.put("sysMenuList" , permissionList) ;
        result.put("roleMenuIds" , roleMenuIds) ;

        // 返回
        return result;
    }


    //给角色分配权限（或菜单）
    @Override
    public void doAssign(AssginMenuDto assginMenuDto) {
        // 根据角色的id删除其所对应的菜单数据
        this.remove(new LambdaQueryWrapper<RolePermission>()
                .eq(RolePermission::getRoleId, assginMenuDto.getRoleId()));

        // 循环添加菜单数据
        List<Map<String, Number>> menuIdList = assginMenuDto.getMenuIdList();

        menuIdList.forEach(menuId -> {
            RolePermission rolePermission = new RolePermission();
            rolePermission.setRoleId(assginMenuDto.getRoleId());
            rolePermission.setPermissionId((Integer) menuId.get("id"));
            rolePermission.setIsHalf(menuId.get("isHalf").intValue());
            this.save(rolePermission) ;
        });


    }



}
